package server;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
//
/**
 * <p>Title: CGIHandler.java</p>
 *
 * <p>Description: Used to handle cgi script requests. It will create a runnable
 * thread which will execute the script on the server and read the output from
 * that script, which will then be sent back to the client.</p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: </p>
 * @author Luping May and Tracie Hong
 * @version 1.0
 */
public class CGIHandler {

  private Request clientRequest;
  private Environment envVariables;
  /**
   * Constructor for CGIHandler class. Used to save the variables necessary for
   * the cgi script to run properly and for the response to be sent back to the
   * client.
   *
   * @param rq Request variable which correlates to the request that was sent
   *   from the client to the server.
   * @param ev Environment variable used to get the state of the server
   *   environment. This information should have been saved when the server was
   *   configured.
   */
  public CGIHandler(Request rq, Environment ev) {
    clientRequest = rq;
    envVariables = ev;
  }

  /**
   * Function used to execute the cgi script that was being requested by the
   * client. 
   * 
   * HINT: Try using the Runtime.getRuntime().exec() function to execute
   * the script. Also look into using both Data and Buffered Streams.
   *
   * @return BufferedInputStream which is the output from the script execution.
   *   This is sent back to the server and then back to the client.
   */
  //public BufferedInputStream runScript() {
    public InputStream runScript(){
    try{

        String[] comd = new String[] {clientRequest.getCGIHandler(), clientRequest.getURI()};
        ProcessBuilder child = new ProcessBuilder(clientRequest.getCGIHandler(), clientRequest.getURI());
        
        String[] temp = clientRequest.getQueryString();
        String key,value;
        for(int i=0; i<temp.length;i++)
        {
            if(temp[i].contains("=")){
                key = temp[i].substring(0, temp[i].indexOf("=")-1);
                value = temp[i].substring(temp[i].indexOf("=")+1, temp[i].length());
                System.out.println("Key:" + key);
                System.out.println("Value:" + value);
                envVariables.addEnvVar(key,value);
            }
        }
        Map<String,String> map = child.environment();
        map.putAll(envVariables.getEnv());
        child.redirectErrorStream(true);
	Process p = child.start();
//        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
//	String line = "";
//	while ((line = input.readLine()) != null) {
//		System.out.println(line);
//	}
//        return new BufferedInputStream (p.getInputStream());
        return p.getInputStream();

//      String[] comd = new String[2];
//        comd[0] = clientRequest.getURI();
//        System.out.println(clientRequest.getURI());
//        System.out.println(clientRequest.getQuery());
//        String[] temp = clientRequest.getQueryString();
//        for(int i=0; i<temp.length;i++)
//        {System.out.println(temp[i]);}
//        System.out.println(clientRequest.getSCRIPTNAME());
//        System.out.println(clientRequest.getCGIHandler());
//        for(int i=0; i<temp.length;i++)
//        envVariables.addEnvVar(temp[i]);
//        comd[1] = clientRequest.getCGIHandler();
//        String[] ENV = envVariables.getEnv();
//        Runtime r = Runtime.getRuntime();
//        Process child = r.exec(comd,ENV);
//        String[] comd = new String[] {clientRequest.getCGIHandler(), clientRequest.getURI()};
//        System.out.println(clientRequest.getURI());
//        System.out.println(clientRequest.getQuery());
//        String[] temp = clientRequest.getQueryString();
//        for(int i=0; i<temp.length;i++)
//        {System.out.println(temp[i]);}
//        System.out.println(clientRequest.getSCRIPTNAME());
//        System.out.println(clientRequest.getCGIHandler());
//        for(int i=0; i<temp.length;i++)
//            envVariables.addEnvVar(temp[i]);
//        String[] ENV = envVariables.getEnv();
//        for(int i=0; i<ENV.length;i++)
//            System.out.println(ENV[i]);
//        Runtime r = Runtime.getRuntime();
//        Process child = r.exec(comd,ENV);
//        return new BufferedInputStream (child.getInputStream());
    }catch (IOException e){
        e.printStackTrace();
    }
    return null;
  }
}
